package com.thread.exe;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//并非Semaphore 真实的实现方式
public class SemaphoreOnLock {
	private final Lock lock = new ReentrantLock();
	private final Condition permitsAvailable = lock.newCondition();
	private int permits;
	
	public SemaphoreOnLock(int initialPermits) {
		try {
			lock.lock();
			permits = initialPermits;
		} finally {
			lock.unlock();
		}
	}
	
	public void aquire() throws InterruptedException {
		try {
			lock.lock();
			while(permits <= 0) {
				permitsAvailable.await();
			}
			permits--;
		} finally {
			lock.unlock();
		}
	}
	
	public void release() {
		try {
			lock.lock();
			permits++;
			permitsAvailable.signal();
		} finally {
			lock.unlock();
		}
	}
}
